package com.ethink.platform.controller.order;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.ethink.framework.common.web.BaseController;
import com.ethink.framework.common.web.context.SPRequestContextHolder;
import com.ethink.framework.common.web.response.CommonResponse;
import com.ethink.mdm.api.MateFacade;
import com.ethink.mdm.api.info.MateSkuInfo;
import com.ethink.order.api.SaleOrderFacade;
import com.ethink.order.api.SaleReturnOrderFacade;
import com.ethink.order.api.enums.SaleReturnOrderOrderTypeEnum;
import com.ethink.order.api.info.*;
import com.ethink.order.api.model.*;
import com.ethink.order.api.request.SaleReturnOrderAddRequest;
import com.ethink.order.api.request.SaleReturnOrderQueryModeRequest;
import com.ethink.order.api.request.SaleReturnOrderQueryRequest;
import com.ethink.order.api.request.SaleReturnOrderUpdateRequest;
import com.ethink.order.api.response.SaleOrderDetailResponse;
import com.ethink.order.api.response.SaleReturnQueryDetailResponse;
import com.ethink.order.api.response.SaleTransferOrderQueryResponse;
import com.ethink.order.api.utils.EthinkStrUtil;
import com.ethink.platform.common.properties.PlatformCommonProperties;
import com.ethink.platform.controller.order.info.ExportInfo;
import com.ethink.platform.manager.ExportManager;
import com.ethink.platform.manager.SaleReturnManager;
import com.ethink.system.api.SystemTodoFacade;
import com.ethink.system.api.enums.SystemTodoTodoTypeEnum;
import com.ethink.system.api.request.SystemTodoAddRequest;
import com.ethink.warehouse.api.SubWarehouseFacade;
import com.ethink.warehouse.api.info.SubWarehouseInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 销售退单 Controller
 *
 * @author default
 * @date 2022-12-09
 */
@Tag(name = "SaleReturnOrderController", description = "销售退单 Controller")
@RestController
@Slf4j
@RequestMapping("platform-server/v1/system-service")
public class SaleReturnOrderController extends BaseController {

    @Autowired
    private SaleReturnOrderFacade saleReturnOrderFacade;

    @Autowired
    private SaleOrderFacade saleOrderFacade;

    @Autowired
    private SubWarehouseFacade subWarehouseFacade;

    @Autowired
    private MateFacade mateFacade;

    @Autowired
    private SaleReturnManager saleReturnManager;

    @Autowired
    private SystemTodoFacade systemTodoFacade;

    @Autowired
    private PlatformCommonProperties commonProperties;

    @Resource
    private ExportManager exportManager;

    @Operation(summary = "销售单转退单查询")
    @GetMapping("/saleReturnOrder/transfer/{id}")
    public CommonResponse<SaleTransferOrderQueryResponse> saleTransferReturnOrderQuery(@PathVariable Long id) {
        SaleTransferOrderQueryResponse response = new SaleTransferOrderQueryResponse();
        SaleOrderDetailResponse saleOrderDetailResponse = saleOrderFacade.getSaleOrderById(id);
        response.setMain(saleOrderDetailResponse.getMain());
        List<SaleReturnDetailOrderInfo> returnInfos = saleReturnOrderFacade.queryDetailListBySaleOrderNo(saleOrderDetailResponse.getMain().getOrderNo());
        Map<String, List<SaleReturnDetailOrderInfo>> returnGroup = returnInfos.stream().collect(Collectors.groupingBy(SaleReturnDetailOrderInfo::getMateSku));
        //mateSku分组
        Map<String, List<SaleDetailOrderModel>> itemMap = saleOrderDetailResponse.getItem().stream()
                .collect(Collectors.groupingBy(SaleDetailOrderModel::getMateSku));
        List<TransferSaleReturnModel> item = new ArrayList<>();
        Integer key = 0;
        for (Map.Entry<String, List<SaleDetailOrderModel>> stringListEntry : itemMap.entrySet()) {
            TransferSaleReturnModel returnModel = new TransferSaleReturnModel();
            List<SaleDetailOrderModel> value = stringListEntry.getValue();
            //计算数量
            int sum = value.stream().mapToInt(SaleDetailOrderModel::getOutQty).sum();
            SaleDetailOrderModel saleDetailOrderModel = value.get(0);
            returnModel.setKey(key);
            returnModel.setOrderNo(saleDetailOrderModel.getOrderNo());
            returnModel.setMateSku(saleDetailOrderModel.getMateSku());
            returnModel.setMateCode(saleDetailOrderModel.getMateCode());
            returnModel.setMateName(saleDetailOrderModel.getMateName());
            returnModel.setMateSkuName(saleDetailOrderModel.getMateSkuName());
            returnModel.setCategoryName(saleDetailOrderModel.getCategoryName());
            returnModel.setBrandCode(saleDetailOrderModel.getBrandCode());
            returnModel.setBrandName(saleDetailOrderModel.getBrandName());
            returnModel.setUnitCode(saleDetailOrderModel.getUnitCode());
            returnModel.setUnitName(saleDetailOrderModel.getUnitName());
            returnModel.setProductSpecification(saleDetailOrderModel.getProductSpecification());
            List<SaleReturnDetailOrderInfo> returnDetailOrderInfos = returnGroup.get(stringListEntry.getKey());
            if (CollUtil.isNotEmpty(returnDetailOrderInfos)) {
                int returnQty = returnDetailOrderInfos.stream().mapToInt(SaleReturnDetailOrderInfo::getReturnQty).sum();
                returnModel.setQty(sum - returnQty);
            } else {
                returnModel.setQty(sum);
            }
            item.add(returnModel);
            key++;
        }
        response.setItem(item);
        return succeedWith(response);
    }

    @Operation(summary = "新增")
    @PostMapping("/saleReturnOrder/add")
    public CommonResponse addSaleReturnOrder(@Validated @RequestBody SaleReturnOrderAddRequest request) {
        request.setCreateUserCode(SPRequestContextHolder.getCurrentSystemUserLoginName());
        request.setCreateUserName(SPRequestContextHolder.getCurrentSystemUserRealName());
        SubWarehouseInfo subWarehouseInfo = subWarehouseFacade.getSubWarehouseByCode(request.getSubWarehouseCode());
        request.setSubWarehouseName(subWarehouseInfo.getSubWarehouseName());
        request.setOrderType(SaleReturnOrderOrderTypeEnum.T3.getIntValue());
        saleReturnOrderFacade.add(request);
        return succeed();
    }

    @Operation(summary = "分页查询")
    @GetMapping("/saleReturnOrder/pageQuery")
    public CommonResponse<List<SaleReturnModel>> querySaleReturnOrder(SaleReturnOrderQueryRequest request) {
        return succeedWithPage(saleReturnOrderFacade.pageQuery(request));
    }

    @Operation(summary = "导出")
    @GetMapping("/saleReturnOrder/export")
    public CommonResponse<ExportInfo> exportSaleReturnOrder(SaleReturnOrderQueryRequest request) {
        return succeedWith(exportManager.exportSaleReturnOrder(request));
    }

    @Operation(summary = "货品模式分页查询")
    @GetMapping("/saleReturnOrder/pageQueryMode")
    public CommonResponse<List<SaleReturnModeModel>> querySaleReturnOrderMode(SaleReturnOrderQueryModeRequest request) {
        return succeedWithPage(saleReturnOrderFacade.pageQueryMode(request));
    }

    @Operation(summary = "货品模式导出")
    @GetMapping("/saleReturnOrder/exportMode")
    public CommonResponse<ExportInfo> exportSaleReturnOrderMode(SaleReturnOrderQueryModeRequest request) {
        return succeedWith(exportManager.exportSaleReturnOrderMode(request));
    }

    @Operation(summary = "详情")
    @GetMapping("/saleReturnOrder/detail/{id}")
    public CommonResponse<SaleReturnQueryDetailResponse> getSaleReturnOrderById(@PathVariable Long id) {
        SaleReturnQueryDetailResponse response = saleReturnOrderFacade.queryDetail(id);
        SaleReturnModel main = response.getMain();
        //查询主仓库信息
        SubWarehouseInfo subWarehouseInfo = subWarehouseFacade.getSubWarehouseByCode(main.getSubWarehouseCode());
        main.setWarehouseCode(subWarehouseInfo.getWarehouseCode());
        main.setWarehouseName(subWarehouseInfo.getWarehouseName());
        List<String> mateSku = CollUtil.getFieldValues(response.getItem(), "mateSku", String.class);
        //填充商品信息
        List<MateSkuInfo> mateSkuInfos = mateFacade.queryMateSkuBySkuCodeList(mateSku);
        Map<String, MateSkuInfo> mateMap = new HashMap<>();
        for (MateSkuInfo mateSkuInfo : mateSkuInfos) {
            mateMap.put(mateSkuInfo.getMateSku(), mateSkuInfo);
        }
        for (SaleReturnDetailModel saleReturnDetailModel : response.getItem()) {
            MateSkuInfo mateSkuInfo = mateMap.get(saleReturnDetailModel.getMateSku());
            if (ObjectUtil.isNotEmpty(mateSkuInfo)) {
                saleReturnDetailModel.setBrandCode(mateSkuInfo.getBrandCode());
                saleReturnDetailModel.setBrandName(mateSkuInfo.getBrandName());
                saleReturnDetailModel.setCategoryName(EthinkStrUtil
                        .stitchStrings(mateSkuInfo.getGeneraCodeName(), mateSkuInfo.getMinorDefectsCodeName(), mateSkuInfo.getSubclassCodeName()));
                saleReturnDetailModel.setMateSkuName(mateSkuInfo.getMateSkuName());
                saleReturnDetailModel.setProductSpecification(mateSkuInfo.getProductSpecification());
                saleReturnDetailModel.setUnitCode(mateSkuInfo.getUnitCode());
                saleReturnDetailModel.setUnitName(mateSkuInfo.getUnitName());
            }
        }
        return succeedWith(response);
    }


    @Operation(summary = "编辑-草稿状态")
    @PutMapping("/saleReturnOrder/update")
    public CommonResponse updateSaleReturnOrder(@Validated @RequestBody SaleReturnOrderUpdateRequest request) {
        saleReturnOrderFacade.update(request);
        return succeed();
    }


    @Operation(summary = "删除-草稿状态")
    @DeleteMapping("/saleReturnOrder/delete/{id}")
    public CommonResponse deleteSaleReturnOrder(@PathVariable("id") Long id) {
        saleReturnOrderFacade.delete(id);
        return succeed();
    }


    @Operation(summary = "审批通过(订单状态 = 2)")
    @PutMapping("/saleReturnOrder/pass/{id}")
    public CommonResponse SaleReturnPass(@PathVariable Long id) {
        saleReturnOrderFacade.pass(id);
        SaleReturnQueryDetailResponse response = saleReturnOrderFacade.queryDetail(id);
        SaleReturnOrderInfo saleReturnOrderInfo = BeanUtil.copyProperties(response.getMain(), SaleReturnOrderInfo.class);
        List<SaleReturnDetailOrderInfo> item = response.getItem().stream()
                .map(a -> BeanUtil.copyProperties(a, SaleReturnDetailOrderInfo.class)).collect(Collectors.toList());
//        List<SaleDetailOrderInfo> tocList = saleOrderFacade.queryDetailListByOrderNo(saleReturnOrderInfo.getSaleOrderNo());
//        List<SaleReturnDetailOrderInfo> tocReturnList = saleReturnOrderFacade.queryDetailListBySaleOrderNo(saleReturnOrderInfo.getSaleOrderNo());
//        List<String> detailOrderNo = CollUtil.getFieldValues(tocList, "detailOrderNo", String.class);
//        List<String> returnDetailNo = CollUtil.getFieldValues(tocReturnList, "detailOrderNo", String.class);
        SaleOrderDetailResponse saleOrderDetailResponse = saleOrderFacade.getSaleOrderByOrderNo(saleReturnOrderInfo.getSaleOrderNo());
        saleReturnManager.t71(saleReturnOrderInfo, item, saleOrderDetailResponse.getMain());
        //创建代办事项
        try {
            SystemTodoAddRequest addRequest = new SystemTodoAddRequest();
            addRequest.setRoleName(commonProperties.getLogisticsRoleName());
            addRequest.setTodoType(SystemTodoTodoTypeEnum.T5.getIntValue());
            addRequest.setDataId(saleReturnOrderInfo.getOrderNo());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderNo", saleReturnOrderInfo.getOrderNo());
            addRequest.setTodoMessage(jsonObject.toJSONString());
            systemTodoFacade.addSystemTodo(addRequest);
        } catch (Exception e) {
            log.error("生成待办失败", e);
        }
        return succeed();
    }


    @Operation(summary = "审批拒绝(订单状态 = 2)")
    @PutMapping("/saleReturnOrder/refuse/{id}")
    public CommonResponse SaleReturnRefuse(@PathVariable Long id) {
        saleReturnOrderFacade.refuse(id);
        return succeed();
    }
}